import 'package:bot_toast/bot_toast.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:toolbox/manager/tools.dart';

import '../common/info.dart';
import '../common/strings.dart';
import '../widgets/defaultDialog.dart';
import 'net/apiManager.dart';

class GlobalUtil {
  static GlobalUtil? _instance;

  GlobalUtil._();

  static PackageInfo? packageInfo;

  static GlobalUtil getInstance() {
    _instance ??= GlobalUtil._();
    return _instance!;
  }

  RxBool hasNewVersion = false.obs;

  ///检测是否是最新版本，是true，否false
  Future<bool> checkVersion(
      {bool showTrue = false, bool alwaysShowDialog = false}) async {
    var res = (await apiManager.getGitReleasesLatestInfo()).data;
    String newVersion = res[Info.gitTagName];
    String newVersionContent = res[Info.gitBody];
    bool isOldVersion = newVersion != ('v${GlobalUtil.packageInfo?.version}');
    if (isOldVersion || alwaysShowDialog) {
      hasNewVersion.value = isOldVersion;
      String title = isOldVersion ? Strings.foundNewVersion : Strings.noNewVersion;
      //新版本下载框
      Get.dialog(
        defaultDialog(
          title: title,
          content: Strings.newVersion(newVersion, newVersionContent),
          sure: isOldVersion ? Strings.update : '查看仓库',
          cancel: Strings.cancel,
          sureFunction: () async {
            String? url;
            if(isOldVersion){
              BotToast.showLoading();
              try {
                var repoInfo = await apiManager.getRepoInfo();
                url = repoInfo.data['homepage'];
              } catch (e) {
                print(e.toString());
              }
              BotToast.closeAllLoading();
              url ??= res['assets'][0]['browser_download_url'];
            }
            url ??= Info.gitHomeUrl;
            launchURL(url);
          },
        ),
      );
      return false;
    } else {
      hasNewVersion.value = false;
      if (showTrue) {
        //提示已是最新版
        showToast(Strings.noNewVersion);
      }
      return true;
    }
  }
}
